const path = require('path');
const resolve = (dir) => path.resolve(__dirname, dir);
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin');
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
const MomentLocalesPlugin = require('moment-locales-webpack-plugin');
const BundleAnalyzerPlugin =
  require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = (env) => {
  const config = {
    entry: './src/index',
    mode: 'development',
    devServer: {
      static: {
        directory: path.join(__dirname, 'dist'),
      },
      historyApiFallback: true,
      open: false,
      port: 3000,
    },
    stats: 'errors-only',
    output: {
      chunkFilename: 'assets/js/[name].[contenthash].js',
      filename: 'assets/js/[name].[contenthash].js',
      clean: true,
      path: resolve('../build'),
      publicPath: '/',
    },
    resolve: {
      alias: {
        '@': resolve('../src'), // 这样配置后 @ 可以指向 src 目录
      },
    },
    optimization: {
      splitChunks: {
        chunks: 'all', // 分割所有模块
        minSize: 30 * 1024, // 分割的文件最小大小
        maxSize: 250 * 1024,
        minChunks: 2, // 引用次数
        maxAsyncRequests: 30, // 最大异步请求数
        maxInitialRequests: 30, // 最大初始化请求数
        automaticNameDelimiter: '~', // 抽离的命名分隔符
        name: false,
        cacheGroups: {
          // 剩余模块自动切分,切分大小是1M
          vendors: {
            // 先抽离第三方库
            test: /[\\/]node_modules[\\/]/,
            priority: -10,
            reuseExistingChunk: true,
            maxSize: 1 * 1024 * 1024, // 切分大小为 1M
            name: 'vendor',
          },
          default: {
            minChunks: 2,
            priority: -20, // 优先级
            reuseExistingChunk: true,
          },
        },
      },
    },

    module: {
      rules: [
        {
          test: /\.js?$/,
          loader: 'babel-loader',
          exclude: /node_modules/,
          options: {
            presets: ['@babel/preset-react'],
          },
        },
        {
          test: /\.(less)$/,
          include: /\.module\.less$/,
          use: [
            {
              loader: 'style-loader',
            },
            {
              loader: 'css-loader',
              options: {
                modules: {
                  localIdentName: '[local]-[hash:base64:8]', // 自定义类名格式
                },
                importLoaders: 1,
              },
            },
            {
              loader: 'less-loader',
              options: {
                lessOptions: {
                  javascriptEnabled: true,
                },
              },
            },
          ],
        },
        {
          test: /\.(less)$/,
          exclude: /\.module\.less$/,
          use: [
            {
              loader: 'style-loader',
            },
            {
              loader: 'css-loader',
            },
            {
              loader: 'less-loader',
              options: {
                lessOptions: {
                  javascriptEnabled: true,
                },
              },
            },
          ],
        },
        {
          test: /\.(css)$/,
          use: [
            {
              loader: 'style-loader',
            },
            {
              loader: 'css-loader',
            },
          ],
        },
        {
          test: /\.svg$/,
          issuer: /\.js?$/,
          use: '@svgr/webpack',
        },
        {
          test: /\.url.svg$/,
          use: ['file-loader'],
        },
        {
          // 小于10k的图片在img下不会有图片文件，而是直接把图片的base64值写到html引入图片的地方
          // 大于10k的图片会放在img下，需要的时候通过http请求下载
          test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
          loader: 'url-loader',
          options: {
            limit: 10000,
          },
        },
        {
          test: /(\.(eot|ttf|woff|woff2|otf)|font)$/,
          loader: 'file-loader',
          options: { outputPath: 'fonts/' },
        },
      ],
    },
    plugins: [
      new FriendlyErrorsPlugin(),
      new HtmlWebpackPlugin({
        template: './public/index.html',
      }),

      new CopyWebpackPlugin([
        {
          from: './public',
        },
      ]),
      new MonacoWebpackPlugin({
        languages: ['sql', 'json', 'css', 'javascript'],
      }),
      new MomentLocalesPlugin({
        localesToKeep: ['zh-cn'],
      }),
    ],
  };
  if (env.analyze === 'true') {
    config.plugins.push(new BundleAnalyzerPlugin());
  }

  return config;
};
